/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DBManager;

import DBTables.TUser;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import java.util.regex.*;

/**
 *
 * @author Иван
 */
public class Registration {

    private String login;
    private String eMail;
    private String information;
    private String password;
    private final String EMAIL_STATEMENT = "[a-zA-Z]{1}[a-zA-Z\\d\\u002E\\u005F]+@([a-zA_Z]+\\u002E){1,2}((com)|(ru)|(org))";
    private final String LOGIN_STATEMENT = "[a-zA-Z\\d]{6,15}";
    private final String PASSWORD_STATEMENT = "[a-zA-Z\\d]{6,15}";
    private final String REGISTRATION_STATEMENT = "Create User ? Identified by ? ";
    private final String SET_GRANT_STATEMENT = "Grant Select,Insert,Update,Delete On *.* To ? Identified by ?";
    private Pattern pattern;
    private Matcher matcher;

    public Registration(String login, String password, String eMail, String information) {
        this.login = login;
        this.password = password;
        this.eMail = eMail;
        this.information = information;
        pattern = null;
        matcher = null;
    }

    public void verifyEnteredData() throws RegistrationException {

        pattern = Pattern.compile(EMAIL_STATEMENT);
        matcher = pattern.matcher(eMail);
        if (!matcher.matches()) {
            throw new RegistrationException("E-MAIL entered incorrect!");
        }

        pattern = Pattern.compile(LOGIN_STATEMENT);
        matcher = pattern.matcher(login);
        if (!matcher.matches()) {
            throw new RegistrationException("LOGIN entered incorrect!");
        }

        pattern = Pattern.compile(PASSWORD_STATEMENT);
        matcher = pattern.matcher(password);
        if (!matcher.matches()) {
            throw new RegistrationException("PASSWORD entered incorrect!");
        }

    }

    public void registrateUser(Connection connection) throws SQLException {

        connection.setAutoCommit(false);

        PreparedStatement prepareStetement;

        prepareStetement = connection.prepareStatement(REGISTRATION_STATEMENT);
        prepareStetement.setString(1, login);
        prepareStetement.setString(2, password);
        prepareStetement.executeUpdate();

        prepareStetement = connection.prepareStatement(SET_GRANT_STATEMENT);
        prepareStetement.setString(1, login);
        prepareStetement.setString(2, password);
        prepareStetement.executeUpdate();

        TUser tableUser = new TUser(connection, "User");
        tableUser.Login = login;
        tableUser.Password = password;
        tableUser.Interests = information;
        tableUser.E_Mail = eMail;
        tableUser.InsertRow();

        connection.setAutoCommit(false);
        connection.commit();
        connection.setAutoCommit(true);

       

    }
}
